<?php

namespace app\admin\controller\shopro;

use app\admin\model\shopro\order\OrderItem;
use think\Db;
use think\exception\HttpResponseException;
use addons\shopro\exception\ShoproException;
use app\admin\model\shopro\Withdraw as WithdrawModel;
use app\admin\model\shopro\WithdrawLog as WithdrawLogModel;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\Admin as AdminModel;
use addons\shopro\service\Withdraw as WithdrawLibrary;
use addons\shopro\library\Operator;

/**
 * 提现
 */
class Withdraw extends Common
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WithdrawModel;
        $this->logModel = new WithdrawLogModel;
    }



    /**
     * 提现列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $withdraws = $this->model->sheepFilter()->with(['user'])->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $withdraws);
    }


    /**
     * 提现日志
     */
    public function log($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $logs = $this->logModel->where('withdraw_id', $id)->order('id desc')->select();
        $morphs = [
            'user' => UserModel::class,
            'admin' => AdminModel::class,
            'system' => AdminModel::class
        ];
        $logs = morph_to($logs, $morphs, ['oper_type', 'oper_id']);
        $logs = $logs->toArray();

        // 解析操作人信息
        foreach ($logs as &$log) {
            $log['oper'] = Operator::info($log['oper_type'], $log['oper'] ?? null);
        }
        $this->success('获取成功', null, $logs);
    }


    public function handle($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->param();
        $action = $params['action'] ?? null;
        $refuse_msg = $params['refuse_msg'] ?? '';
        if ($action == 'refuse' && !$refuse_msg) {
            $this->error('请输入拒绝原因');
        }

        $ids = is_array($id) ? $id : explode(',', $id);
        foreach ($ids as $key => $id) {
            Db::startTrans();
            try {
                $withdraw = $this->model->lock(true)->where('id', $id)->find();
                if (!$withdraw) {
                    $this->error(__('No Results were found'));
                }
                $withdrawLib = new WithdrawLibrary($withdraw->user_id);

                switch ($action) {
                    case 'agree':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        break;
                    case 'agree&withdraw':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'withdraw':
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'refuse':
                        $withdraw = $withdrawLib->handleRefuse($withdraw, $refuse_msg);
                        break;
                }

                Db::commit();
            } catch (ShoproException $e) {
                Db::commit();       // 不回滚，记录错误日志
                $this->error($e->getMessage());
            } catch (HttpResponseException $e) {
                $data = $e->getResponse()->getData();
                $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                $this->error($message);
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->success('处理成功');
    }

    /*
     * 导出
     * */
    public function exportDelivery()
    {
        $cellTitles = [
            // 订单表字段
            'id' => 'Id',
            'user_id' => '申请用户',
            'paid_fee' => '实际到账',
            'amount' => '提现金额',
            'charge_rate' => '费率',
            'charge_fee' => '手续费',
            'withdraw_type' => '提现方式',
            'withdraw_info' => '打款信息',
            'createtime' => '申请时间',
            'status' => '状态',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->count();      // nosend 加了 noApplyRefund
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '提现列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
            'sub_start_cell' => '',
            'sub_field' => ''
        ];

        $result = $export->export($params, function ($pages) use (&$total) {
            // 未申请全额退款的
            $datas = $this->model->sheepFilter()
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();

            $datas = collection($datas)->toArray();

            $newDatas = [];
            foreach ($datas as &$order) {
                $withdraw_type = $this->model->getWithdrawTypeTextAttr($order['withdraw_type'],$order);
                if($order['status']==-1){
                    $status='已拒绝';
                }elseif ($order['status']==0){
                    $status='待审核';
                }elseif ($order['status']==1){
                    $status='处理中';
                }elseif ($order['status']==2){
                    $status='已处理';
                }
                $data = [
                    'id' => $order['id'],
                    'user_id' => db::name('user')->where('id',$order['user_id'])->value('mobile'),
                  //  'user_id' => $order['user_id'],
                    'paid_fee' => $order['paid_fee'],
                    'amount' => $order['amount'],
                    'charge_rate' => $order['charge_rate'],
                    'charge_fee' => $order['charge_fee'],
                    'withdraw_type' => $withdraw_type,
                    'withdraw_info' => implode(',',$order['withdraw_info']),
                    'createtime' => $order['createtime'],
                    'status' => $status,
                ];
                $newDatas[] = $data;
            };

            if ($pages['is_last_page']) {
                $newDatas[] = ['order_id' => "总数：" . $total . "；"];
            }
            return $newDatas;
        });
        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
